package com.solution.common.utils.upload;

import java.io.FileNotFoundException;
import java.io.InputStream;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.solution.common.config.PublicConfig;

public class OssTemplate {

	private static String endpoint = PublicConfig.END_POINT;
	private static String accessKeyId = PublicConfig.ACCESS_KEY_ID;
	private static String accessKeySecret = PublicConfig.ACCESS_KEY_SECRET;

	/**
	 * Bucket是OSS全局命名空间，相当于数据的容器，可以存储若干Object
	 * @param bucketName
	 */
	public static void createBucket(String bucketName) {
		// 初始化OSSClient
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		// 新建一个Bucket
		client.createBucket(bucketName);
	}

	/**
	 * Object是OSS中最基本的数据单元，您可以把它简单地理解为文件，用下面代码可以实现一个Object的上传：
	 * @param bucketName
	 * @param key
	 * @param filePath
	 * @throws FileNotFoundException
	 */
	public static void putObject(String bucketName, String key, InputStream inputStream, long contentLength) {
		// 初始化OSSClient
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();
		// 必须设置ContentLength
		meta.setContentLength(contentLength);
		// 上传Object.
		PutObjectResult result = client.putObject(bucketName, key, inputStream, meta);
		client.shutdown();
		// 打印ETag
		System.out.println("上传成功：" + result.getETag());
	}

	/**
	 * 完成一系列上传后，可能需要查看某个Bucket中有哪些Object，可以通过下面的程序实现：
	 * 
	 * @param bucketName
	 */
	public void listObjects(String bucketName) {

		// 初始化OSSClient
		OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 获取指定bucket下的所有Object信息
		ObjectListing listing = client.listObjects(bucketName);
		client.listBuckets().contains("zhaiugo");

		// 遍历所有Object
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			// System.out.println("dujiewei2:"+objectSummary.getKey());
		}
	}

	/**
	 * 把Bucket设置为所有人可读
	 * 
	 * @param client
	 * @param bucketName
	 * @throws OSSException
	 * @throws ClientException
	 */
	// private static void setBucketPublicReadable(OSSClient client, String
	// bucketName) throws OSSException, ClientException {
	// //创建bucket
	// client.createBucket(bucketName);
	//
	// //设置bucket的访问权限，public-read-write权限
	// client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
	// }
}
